package javabase.concurrency;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fance
 * @date 2018/6/10 9:36
 */
class MultiThread extends Thread {
    private int tid;

    public MultiThread(int tid) {
        this.tid = tid;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; ++i) {
                Thread.sleep(100);
                System.out.println(String.format("T%d:%d", tid, i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Producer implements Runnable {
    private BlockingQueue<String> queue;

    public Producer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 20; ++i) {
                Thread.sleep(1000);
                queue.put(String.valueOf(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Consumer implements Runnable {
    private BlockingQueue<String> queue;

    public Consumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
           while (true) {
               System.out.println(Thread.currentThread().getName() +
               " : " + queue.take());
           }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class MultiThreadTest {

    public static void testThread() {
        for (int i = 0; i < 10; i++) {
            final int tid = i;
            new Thread(() -> {
                try {
                    for (int i1 = 0; i1 < 10; ++i1) {
                        Thread.sleep(1000);
                        System.out.println(String.format("T2 %d : %d", tid, i1));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static Object obj = new Object();
    public static void testSynchronized1() {
        synchronized (obj) {
            try {
                for (int i = 0; i < 10; ++i) {
                    Thread.sleep(1000);
                    System.out.println(String.format("T3%d", i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void testSynchronized2() {
        synchronized (new Object()) {
            try {
                for (int i = 0; i < 10; ++i) {
                    Thread.sleep(1000);
                    System.out.println(String.format("T4%d", i));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void testBlockingQueue() {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue),"consumer 1").start();
        new Thread(new Consumer(queue),"consumer 2").start();
    }

    public static int counter = 0;
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static void sleep(int mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void testWithAtomic() {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                sleep(1000);
                for (int j = 0; j < 10; j++) {
                    System.out.println(atomicInteger.incrementAndGet());
                }
            }).start();
        }
    }

    public static void testWithoutAtomic() {
        for (int i = 0; i < 10; ++i) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sleep(1000);
                    for (int j = 0; j < 10; ++j) {
                        counter++;
                        System.out.println(counter);
                    }
                }
            }).start();
        }
    }

    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    private static int userId;
    public  static void testThreadLocal() {
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            new Thread(()-> {
                threadLocal.set(finalI);
                sleep(1000);
                System.out.println("ThreadLocal: " + threadLocal.get());
            }).start();
        }

        for (int i = 0; i < 10; ++i) {
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    userId = finalI;
                    sleep(1000);
                    System.out.println("NonThreadLocal: " + userId);
                }
            }).start();
        }
    }


    public static void testExecutor() {
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.submit(() -> {
            for (int i = 0; i < 10; i++) {
                sleep(1000);
                System.out.println("Execute1 " + i);
            }
        });

        service.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; ++i) {
                    sleep(1000);
                    System.out.println("Execute2 " + i);
                }
            }
        });
        service.shutdown();
        while (!service.isTerminated()) {
            sleep(1000);
            System.out.println("Wait for termination.");
        }
    }


    public static void testFutrue() {
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<Integer> future = service.submit(() -> {
            sleep(1000);
            return 1;
        });

        service.shutdown();
        try {
            System.out.println(future.get());
            //System.out.println(future.get(100, TimeUnit.MILLISECONDS));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        //testThread();
       /* testSynchronized1();
        testSynchronized2();*/
       // testBlockingQueue();
      // testWithAtomic();
       // testWithoutAtomic();
       // testThreadLocal();
       // testExecutor();
        testFutrue();
    }


}
